package com.offcn.test;

import sun.misc.Unsafe;

/**
 * Unsafe类操作对象属性
 */
public class UnsafeTest2 {
    public static void main(String[] args) throws Exception {
        Unsafe unsafe = UnsafeUtil.getUnsafe();
        //获取指定属性在内存中的偏移量
        //静态成员
        long nameOffset = unsafe.staticFieldOffset(User2.class.getDeclaredField("name"));
        System.out.println("nameOffset:"+nameOffset);
        //非静态成员
        long telOffset = unsafe.objectFieldOffset(User2.class.getDeclaredField("tel"));
        System.out.println("telOffset:"+telOffset);

        //创建对象,开辟空间
        User2 user2 = new User2();
        //给属性赋值
        unsafe.putObject(user2,nameOffset,"mingren");
        unsafe.putObject(user2,telOffset,"13132131211");
        //取出属性值(取出指定空间的数据)
        String name = unsafe.getObject(user2,nameOffset).toString();
        String tel = unsafe.getObject(user2,telOffset).toString();
        System.out.println("name="+name+";tel="+tel);
    }
}

class User2{
    //静态成员变量
    private static String name = "kakaxi";
    //非静态成员变量
    private String tel = "182811901919";
}
